package top.mingyi4cjh.cms.common.interceptor;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import top.mingyi4cjh.cms.common.error.EmBusinessError;
import top.mingyi4cjh.cms.common.error.HandlerError;
import top.mingyi4cjh.cms.common.response.CommonReturnType;
import top.mingyi4cjh.cms.common.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author MingYi
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //token建议是存放在header中，所以约定使用header传token
        String token = request.getHeader("token");

        HandlerError handlerError = null;
        try {
            //验证令牌
            JwtUtils.verify(token);
            //放行请求
            return true;
        } catch (SignatureVerificationException e) {
            handlerError = new HandlerError(EmBusinessError.INVALID_SIGNATURE);
        } catch (TokenExpiredException e) {
            handlerError = new HandlerError(EmBusinessError.TOKEN_EXPIRED);
        } catch (Exception e) {
            // 为了安全，AlgorithmMismatchException抛出的是无效信息的异常，不是无效算法异常，就合并了
            handlerError = new HandlerError(EmBusinessError.INVALID_TOKEN);
        }

        //返回错误信息
        String json = new ObjectMapper().writeValueAsString(CommonReturnType.create(handlerError, "fail"));
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);

        return false;
    }
}